from PyQt5.QtWidgets import QMainWindow, QLineEdit, QPushButton, QVBoxLayout, QWidget, QMessageBox, QApplication
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEnginePage, QWebEngineProfile, QWebEngineSettings
from PyQt5.QtCore import QUrl
import os
import shutil
import sys

class BrowserWindow(QMainWindow):
    def __init__(self):
        super(BrowserWindow, self).__init__()
        self.setWindowTitle('问吧助手')  # 窗口标题

        # 设置窗口的初始大小，模拟常见移动设备的屏幕尺寸
        self.setGeometry(5, 30, 410, 740)  # 410x740 是一个常见的智能手机屏幕尺寸

        try:
            # 创建一个 QWebEngineProfile 并设置为默认配置
            profile = QWebEngineProfile.defaultProfile()

            # 清空缓存
            cache_path = profile.cachePath()
            persistent_storage_path = profile.persistentStoragePath()

            if cache_path and os.path.exists(cache_path):
                shutil.rmtree(cache_path, ignore_errors=True)
                os.makedirs(cache_path, exist_ok=True)

            if persistent_storage_path and os.path.exists(persistent_storage_path):
                shutil.rmtree(persistent_storage_path, ignore_errors=True)
                os.makedirs(persistent_storage_path, exist_ok=True)

            # 创建一个 QWebEnginePage 并设置用户代理字符串，模拟 Android 13 设备
            page = QWebEnginePage(profile, self)
            user_agent = "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1 Edg/128.0.0.0"
            page.profile().setHttpUserAgent(user_agent)

            # 设置 WebEngineSettings
            settings = page.settings()
            settings.setAttribute(QWebEngineSettings.JavascriptEnabled, True)
            settings.setAttribute(QWebEngineSettings.PluginsEnabled, True)
            settings.setAttribute(QWebEngineSettings.AutoLoadImages, True)
            settings.setAttribute(QWebEngineSettings.LocalContentCanAccessRemoteUrls, True)

            # 创建 QWebEngineView 并设置页面
            self.browser = QWebEngineView()
            self.browser.setPage(page)

            # 设置初始缩放比例
            self.browser.setZoomFactor(1.0)

            # 创建地址栏
            self.url_bar = QLineEdit()
            self.url_bar.returnPressed.connect(self.navigate_to_url)

            # 创建加载按钮
            self.load_button = QPushButton("加载")
            self.load_button.clicked.connect(self.navigate_to_url)

            # 创建布局并将控件添加到布局中
            layout = QVBoxLayout()
            layout.addWidget(self.url_bar)
            layout.addWidget(self.load_button)
            layout.addWidget(self.browser)

            container = QWidget()
            container.setLayout(layout)
            self.setCentralWidget(container)

            # 加载初始页面
            self.browser.load(QUrl('http://toolkit.wenba.gd.cn'))

            # 初始化网络状态变量
            self.is_network_connected = True

        except Exception as e:
            QMessageBox.critical(self, '初始化错误', f'初始化时发生错误: {e}')
            sys.exit(1)

    def navigate_to_url(self):
        """当用户按下回车或点击加载按钮时调用此方法"""
        q = QUrl(self.url_bar.text())
        if q.scheme() == "":
            q.setScheme("http")
        self.browser.load(q)

    def closeEvent(self, event):
        # 创建一个消息框询问用户是否真的要退出
        reply = QMessageBox.question(self, '窗口关闭', '您确定要关闭窗口吗？',
                                     QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if reply == QMessageBox.Yes:
            self.hide()
        else:
            event.ignore()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = BrowserWindow()
    window.show()
    sys.exit(app.exec_())
# 注意：这个代码片段假设你已经有了一个 QApplication 实例，并且你将 BrowserWindow 类实例化以显示窗口。
# pyinstaller --onefile --windowed --add-data "update.bat;." --icon "wenbalogo.icon"  --upx-dir D:\software\upx testBrowser.py
